

package com.hazelcast.internal.management.operation;

import com.hazelcast.config.PermissionConfig;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.management.ManagementDataSerializerHook;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.impl.Versioned;
import com.hazelcast.spi.exception.RetryableHazelcastException;
import com.hazelcast.spi.impl.AllowedDuringPassiveState;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Propagates {@link PermissionConfig} changes to members.
 */
public class UpdatePermissionConfigOperation extends AbstractManagementOperation implements AllowedDuringPassiveState, Versioned {

    private Set<PermissionConfig> permissionConfigs;

    public UpdatePermissionConfigOperation() {
    }

    @SuppressWarnings("unused")
    public UpdatePermissionConfigOperation(Set<PermissionConfig> permissionConfigs) {
        this.permissionConfigs = permissionConfigs;
    }

    @Override
    public int getClassId() {
        return ManagementDataSerializerHook.UPDATE_PERMISSION_CONFIG_OPERATION;
    }

    @Override
    public void run() throws Exception {
        Node node = getNodeEngine().getNode();
        try {
            node.securityContext.refreshPermissions(permissionConfigs);
        } catch (IllegalStateException e) {
            throw new RetryableHazelcastException("Permission refresh was not allowed at this time", e);
        }
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeInt(permissionConfigs.size());
        for (PermissionConfig permissionConfig : permissionConfigs) {
            permissionConfig.writeData(out);
        }
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        int configSize = in.readInt();
        permissionConfigs = new HashSet<>(configSize);
        for (int i = 0; i < configSize; i++) {
            PermissionConfig permissionConfig = new PermissionConfig();
            permissionConfig.readData(in);
            permissionConfigs.add(permissionConfig);
        }
    }
}
